package com.yaukie.socket.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yaukie.socket.constant.Constants;
import com.yaukie.socket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;

/**
 * @功能名称： 缓存消息接收器，用于监听频道消息
 * @功能描述：  缓存消息接收器，用于监听频道消息
 * @作者： yuenbin
 * @创建时间： 9:43 2023/7/24
 * @Motto： It is better to be clear than to be clever !
 **/
@Component
 public class RedisListener implements MessageListener {

    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired(required = false)
    private WebSocketServer  webSocketServer;

    @Override
    public void onMessage(Message message, byte[] bytes) {
       String channel = new String(message.getChannel());
        String msg = null ;
        try {
              msg = new String(message.getBody(),"UTF-8") ;
            if(!StringUtils.isEmpty(msg)){
                if(channel.equalsIgnoreCase(Constants.REDIS_CHANNEL_ID)){
                    JSONObject jsonObject = JSON.parseObject(msg);
                    webSocketServer.sendMsgByTopicId((String)jsonObject.get(Constants.SOCKET_REDIS_KEY),(String) jsonObject.get(Constants.SOCKET_REDIS_VAL));
                }

            }
        } catch (UnsupportedEncodingException e) {
            log.error("处理消息异常："+e.toString());
        }

    }

}
